//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;

using CommunityServer.Components;

namespace CommunityServer.Blogs.Components
{
    /// <summary>
    /// Summary description for WeblogRssHandler.
    /// </summary>
    public class WeblogAtomHandler : BaseWeblogSyndicationHandler
    {
        public WeblogAtomHandler()
        {
        }

        protected override string CacheKey
        {
			get
			{
				return string.Format("Weblog:{0}:IndividualAtom",CurrentSection.SectionID);
			}
        }

        /// <summary>
        /// Override Process feed to check if an external feed exists
        /// </summary>
        protected override void ProcessFeed()
        {
			// If an external feed url exists for this blog, redirect there unless this handler
			//	is being accessed via the private url
			if (!Globals.IsNullorEmpty(((Weblog)CurrentSection).ExternalFeedUrl))
			{
				if (Context.Request.QueryString["private"] == null)
				{
					Context.Response.RedirectLocation = ((Weblog)CurrentSection).ExternalFeedUrl;
					Context.Response.StatusCode = 301;
					Context.Response.End();
				}
			}
			
            base.ProcessFeed();
        }

        protected override CachedFeed BuildFeed()
        {
            
            BlogThreadQuery query = BlogThreadQuery.CreateNewSingleBlogQuery(CurrentSection.SectionID);
			query.BlogPostType = BlogPostType.Post;
            query.PageIndex = 0;
            query.PageSize = BlogConfig.IndividualPostCount;
            query.PostConfig = BlogPostConfig.IsAggregated;
            query.FirstPageOnly = false;

            ThreadSet threads = WeblogPosts.GetBlogThreads(query,true);
            WeblogAtomWriter writer = null;

			writer = new WeblogAtomWriter(threads.Threads,this.CurrentWeblog,this.BaseUrl);
            DateTime dt =  threads.Threads.Count > 0 ? ((WeblogPost)threads.Threads[0]).PostDate : DateTime.Now;
            
            return new CachedFeed(dt,null,writer.GetXml());

        }

    }
}
